What is semver-compare?
The semver-compare npm package is a simple utility for comparing semantic version strings. It allows developers to determine the order of semantic versions, check if one version is greater than, less than, or equal to another, and sort arrays of version strings.
What are semver-compare's main functionalities?
Compare two semantic version strings
This feature allows you to compare two semantic version strings and returns -1, 0, or 1 depending on whether the first version is less than, equal to, or greater than the second version.
"const compare = require('semver-compare');
let result = compare('1.2.3', '1.2.4');
console.log(result); // -1"
Sort an array of semantic version strings
This feature allows you to sort an array of semantic version strings in ascending order using the compare function provided by the package.
"const compare = require('semver-compare');
let versions = ['1.2.3', '1.2.4', '1.2.2'];
versions.sort(compare);
console.log(versions); // ['1.2.2', '1.2.3', '1.2.4']"
Other packages similar to semver-compare
semver
The semver package is a more comprehensive tool for working with semantic versions. It provides functions for parsing, comparing, and manipulating semantic versions. It includes a wider range of features compared to semver-compare, such as coercion, ranges, and version incrementing.
compare-versions
compare-versions is another package that allows for comparison of semantic version strings. It offers similar basic comparison functionality to semver-compare but also includes additional options for custom sorting and comparing version segments individually.
semver-compare
compare two semver version strings, returning -1, 0, or 1
The return value can be fed straight into [].sort
.
example
var cmp = require('semver-compare');
var versions = [
'1.2.3',
'4.11.6',
'4.2.0',
'1.5.19',
'1.5.5',
'4.1.3',
'2.3.1',
'10.5.5',
'11.3.0'
];
console.log(versions.sort(cmp).join('\n'));
prints:
1.2.3
1.5.5
1.5.19
2.3.1
4.1.3
4.2.0
4.11.6
10.5.5
11.3.0
whereas the default lexicographic sort (versions.sort()
) would be:
1.2.3
1.5.19
1.5.5
10.5.5
11.3.0
2.3.1
4.1.3
4.11.6
4.2.0
methods
var cmp = require('semver-compare')
cmp(a, b)
If the semver string a
is greater than b
, return 1
.
If the semver string b
is greater than a
, return -1
.
If a
equals b
, return 0;
install
With npm do:
npm install semver-compare
license
MIT